package structure.algorithm.leetcode;

import java.math.BigInteger;

public class AddTwoNumbers {
    String listNodeToString(ListNode l) {
        StringBuilder sb = new StringBuilder();
        while (l.val >= 0) {
            int a = l.val;
            sb.insert(0, a);
            if (l.next == null) {
                break;
            }
            l = l.next;
        }
        return sb.toString();
    }
    
    ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        BigInteger a = new BigInteger(listNodeToString(l1)).add(new BigInteger(listNodeToString(l2)));
        String s = String.valueOf(a);
        ListNode l = null;
        ListNode lt = null;
        for (int b = 0; b < s.length(); b++) {
            if (b == 0) {
                char c = s.charAt(s.length() - b - 1);
                lt = new ListNode(Integer.parseInt(String.valueOf(c)));
                l = lt;
            }
            if (b + 1 < s.length()) {
                char d = s.charAt(s.length() - b - 2);
                lt.next = new ListNode(Integer.parseInt(String.valueOf(d)));
                lt = lt.next;
            }
        }
        return l;
    }
}
